import { CardCategory, UaCard } from "../../../models/ua-card.model";
import { UaIpEntity } from "../../../models/ua-ip.model";
import { UaSheetCard, UaUserDeckDto } from "../../../models/ua-user-deck.model";
import { GlobalService } from "../../../services/global.service";
import { UaIpService } from "../../../services/ua-ip.service";
import { UserDeckService } from "../../../services/ua-user-deck.service";
let rewardedVideoAd: WechatMiniprogram.RewardedVideoAd | null = null
// pages/share/deck-share/deck-share.page.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgData: GlobalService.FILE_HOST + `/common/sheet2.png`,
    loading: true
  },

  customData: {
    ipId: 0,
    deckId: 0,
    ipTitle: '',
    deck: undefined as UaUserDeckDto | undefined,
    idCardMap: {} as { [key: number]: UaCard },
    categoryCountMap: {} as { [key: string]: number },
    sheetCardList: [] as UaSheetCard[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    this.customData.deckId = options.deckId;
    this.customData.ipId = options.ipId;

    wx.setNavigationBarTitle({
      title: '卡表'
    });
    this.showAd();

    UaIpService.fetchUaIp(this.customData.ipId!).then((response: UaIpEntity) => {
      if (response) {
        this.customData.ipTitle = response.ipTitle!;
      }
    });
    // UaCardService.findListByIpId(this.customData.ipId!).then(async (response: UaCard[]) => {
    this.initDeck();
    // });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  initDeck() {
    const deckMap: { [key: string]: UaSheetCard } = {};
    UserDeckService.findById(this.customData.deckId!).then(async (response: UaUserDeckDto) => {
      if (response) {
        const cardMap: { [key: number]: UaCard } = {};
        (response.cardDtoList ?? []).map((card: UaCard) => {
          cardMap[card.id!] = card;
        });
        this.customData.idCardMap = cardMap;
        this.customData.deck = response;

        for (const item of this.customData.deck!.cardList ?? []) {
          const card = this.customData.idCardMap[item.id]
          if (card.cardCategory) {
            if (!this.customData.categoryCountMap[card.cardCategory.toString().toLowerCase()]) {
              this.customData.categoryCountMap[card.cardCategory.toString().toLowerCase()] = 0;
            }
            this.customData.categoryCountMap[card.cardCategory.toString().toLowerCase()] += item.count;
          }
          if (!deckMap[card.cardNo!]) {
            deckMap[card.cardNo!] = {
              count: item.count,
              cardNo: card.cardNo,
              cardName: card.cardName
            }
          } else {
            deckMap[card.cardNo!].count! += item.count!;
          }
        }
        const keys = Object.keys(deckMap);
        this.customData.sheetCardList = [];
        for (const key of keys) {
          this.customData.sheetCardList.push(deckMap[key]!);
        }
        await this.startDraw();
      }
    })
  },

  async startDraw() {
    const canvas = wx.createOffscreenCanvas({ type: '2d', width: 2481, height: 3508 })
    const context = canvas.getContext('2d');
    // Slogan
    await this.drawImg(canvas, context, {
      startX: 0,
      startY: 0,
      width: 2481,
      height: 3508
    }, GlobalService.FILE_HOST + `/common/sheet2.png`);


    const h = 67;
    const top = 800;
    let i = 0;

    for (const item of this.customData.sheetCardList) {
      // await this.drawImg(canvas, context, {
      //   startX: left + c * (w + marginH),
      //   startY: top + r * (w * 1.4 + marginV),
      //   width: w,
      //   height: w * 1.4
      // }, GlobalService.FILE_HOST + this.customData.idCardMap[item.id].cardImg);

      // this.drawRect(
      //   context, {
      //   startX: left + c * (w + marginH),
      //   startY: top + r * (w * 1.4 + marginV) + w * 1.4 - 60,
      //   width: 60,
      //   height: 60
      // },
      //   "rgba(0,0,0,0.8)"
      // );
      if (item.count === 0) continue;
      this.drawText(context, {
        startX: 260 + Math.floor(i / 25) * 1090,
        startY: top + i % 25 * h,
      }, item.cardNo!, 32)
      this.drawText(context, {
        startX: 665 + Math.floor(i / 25) * 1110,
        startY: top + i % 25 * h - (item.cardName!.length > 13 ? 4 : 0),
      }, item.cardName!, item.cardName!.length > 13 ? 24 : 32)
      this.drawText(context, {
        startX: 1140 + Math.floor(i / 25) * 1130,
        startY: top + i % 25 * h,
      }, item.count!.toString(), 36)
      i++;
    }

    // const bottom = top + Math.ceil(this.customData.deck!.cardList!.length / 6) * (w * 1.4 + marginV);

    // LOGO
    // await this.drawImg(canvas, context, {
    //   startX: 50,
    //   startY: bottom,
    //   width: 280,
    //   height: 280
    // }, GlobalService.FILE_HOST + this.customData.logo);


    // if (this.customData.ipTitle!.length < 10) {
    //   this.drawText(context, {
    //     startX: 285,
    //     startY: 1634,
    //   }, this.customData.ipTitle, 20);
    // } else {
    //   this.drawText(context, {
    //     startX: 285,
    //     startY: 1634,
    //   }, this.customData.ipTitle, 16);
    // }

    let c = this.customData.categoryCountMap[CardCategory.Character.toLowerCase()!] ?? 0;
    this.drawText(context, {
      startX: 670 + (c < 10 ? 10 : 0),
      startY: 2690
    }, c.toString(), 45)
    c = this.customData.categoryCountMap[CardCategory.Field.toLowerCase()!] ?? 0;
    this.drawText(context, {
      startX: 670 + (c < 10 ? 10 : 0),
      startY: 2755,
    }, c.toString(), 45)
    c = this.customData.categoryCountMap[CardCategory.Event.toLowerCase()!] ?? 0;
    this.drawText(context, {
      startX: 670 + (c < 10 ? 10 : 0),
      startY: 2820,
    }, c.toString(), 45)

    const imgData = context.canvas.toDataURL();
    this.setData({
      imgData,
      loading: false
    });
  },

  async drawImg(canvas: any, context: any, position: {
    startX: number,
    startY: number,
    width: number,
    height: number
  }, url: string) {
    context.save();
    const image = canvas.createImage();
    await new Promise(resolve => {
      image.onload = resolve;
      image.src = url;
    });
    let x = 0;
    let y = 0;
    let w = position.width;
    let h = position.height;
    let r = Math.min(w / image.width, h / image.height);

    w = image.width * r;
    h = image.height * r;
    x = (position.width - w) / 2;
    y = (position.height - h) / 2;

    context.drawImage(image, x + position.startX, y + position.startY, w, h);
    context.restore();
  },

  drawText(context: any, position: {
    startX: number,
    startY: number,
    width?: number
  }, text: string, size?: number, color?: string) {
    context.save();
    context.fillStyle = color ? color : '#000000';
    context.font = (size ? size : 32) + 'px sans-serif';
    context.fillText(text, position.startX, position.startY);
    context.restore();
  },

  drawRect(context: any, position: {
    startX: number,
    startY: number,
    width: number,
    height: number
  }, color?: string) {
    context.save();
    context.fillStyle = color ? color : '#000000';
    context.fillRect(position.startX, position.startY, position.width, position.height);
    context.restore();
  },

  beforeSave() {
    if (rewardedVideoAd) {
      rewardedVideoAd.show().catch(() => {
        // 失败重试
        rewardedVideoAd!.load()
          .then(() => rewardedVideoAd!.show())
          .catch(err => {
            console.error('激励视频 广告显示失败', err);
            this.save()
          })
      })
    }
  },

  save() {
    const data = this.data.imgData.replace('data:image/png;base64,', '');
    const fm = wx.getFileSystemManager(); // 获取文件管理器对象
    const filePath = wx.env.USER_DATA_PATH + '/ua_' + Date.now() + '.png';
    fm.writeFile({
      filePath, // 表示生成一个临时文件名
      data,
      encoding: 'base64',
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath,
          success: (res) => {
            wx.showToast({
              title: '保存成功',
            });
          },
          fail: (err) => {
            console.log(err)
          }
        })
        console.log(res)
      }, fail: err => {
        console.log(err)
      }
    });
  },

  showAd() {
    // 若在开发者工具中无法预览广告，请切换开发者工具中的基础库版本
    // 在页面中定义插屏广告
    let interstitialAd = null

    // 在页面onLoad回调事件中创建插屏广告实例
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-8bc3232a5734138d'
      })
      interstitialAd.onLoad(() => { })
      interstitialAd.onError((err) => {
        console.error('插屏广告加载失败', err)

      })
      interstitialAd.onClose(() => { })
    }

    // 在适合的场景显示插屏广告
    if (interstitialAd) {
      interstitialAd.show().catch((err) => {
        console.error('插屏广告显示失败', err)
      })
    }

    if (wx.createRewardedVideoAd) {
      rewardedVideoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-c51c60ef3e17e626'
      });
      rewardedVideoAd.onLoad(() => {
        console.log('onLoad event emit')
      });
      rewardedVideoAd.onError((err) => {
        console.log('onError event emit', err)
      });
      rewardedVideoAd.onClose(res => {
        // 用户点击了【关闭广告】按钮
        if (res && res.isEnded) {
          // 正常播放结束，可以下发游戏奖励
          this.save();
        } else {
          // 播放中途退出，不下发游戏奖励
        }
      })

    }
  }

})